// https://leetcode.cn/problems/sort-an-array/description/

// 算法思路总结：
// 1. 归并排序实现数组排序
// 2. 递归分割数组至单个元素后合并
// 3. 合并时按顺序比较左右子数组元素
// 4. 使用临时数组存储合并结果
// 5. 时间复杂度：O(n log n)，空间复杂度：O(n)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>

class Solution 
{
public:
    vector<int> sortArray(vector<int>& nums)
    {
        mergesort(nums, 0, nums.size() - 1);
        return nums;
    }

    void mergesort(vector<int>& nums, int left, int right)
    {
        if (left >= right)
        {
            return ;
        }

        int mid = (left + right) >> 1;
        mergesort(nums, left, mid);
        mergesort(nums, mid + 1, right);

        int cur1 = left, cur2 = mid + 1, index = 0;
        vector<int> tmp(right - left + 1);

        while (cur1 <= mid && cur2 <= right)
        {
            if (nums[cur1] <= nums[cur2])
            {
                tmp[index++] = nums[cur1++];
            }
            else
            {
                tmp[index++] = nums[cur2++];
            }
        }

        while (cur1 <= mid)
        {
            tmp[index++] = nums[cur1++];
        }

        while (cur2 <= right)
        {
            tmp[index++] = nums[cur2++];
        }

        for (int i = left ; i <= right ; i++)
        {
            nums[i] = tmp[i - left];
        }
    }
};

int main()
{
    vector<int> nums1 = {5,2,3,1}, nums2 = {5,1,1,2,0,0};
    Solution sol;

    sol.sortArray(nums1);
    sol.sortArray(nums2);

    for (const int& num : nums1)
        cout << num << " ";
    cout << endl;

    for (const int& num : nums2)
        cout << num << " ";
    cout << endl;

    return 0;
}